<?php
require_once('functions/pageLoad.php');

loginRequired();
$user_session = explode("_", $_SESSION['user']);
$user_id = $user_session[0];

$page_title = 'Post a job';

if($_SERVER['REQUEST_METHOD'] == 'POST'){

// HANDLE IMAGES

	require_once('functions/imageScale.php');

	$rootPath = $_SERVER['DOCUMENT_ROOT'].'/public_images/';

	if(isset($_FILES['image_1']['tmp_name']) && strlen($_FILES['image_1']['tmp_name']) > 0){

	$imageName = $_FILES['image_1']['tmp_name'];
	$newImageName = $user_id.'-'.mktime().'-1';

	//large dimensions
	$maxWidth = '700';
	$maxHeight = '466';
	$imgScale1a = imageScale($rootPath.'large/', $imageName, $newImageName, $maxWidth, $maxHeight);

	//small dimensions
	$maxWidth = '108';
	$maxHeight = '300';
	$imgScale1b = imageScale($rootPath.'small/', $imageName, $newImageName, $maxWidth, $maxHeight);

	if(strlen($imgScale1a['error']) == 0){
	// add image 1 to db

	$sql = "INSERT INTO images (string) VALUES ('".$imgScale1a['image']."')";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$img1_id = mysql_insert_id();

	}

	}

	if(isset($_FILES['image_2']['tmp_name']) && strlen($_FILES['image_2']['tmp_name']) > 0){

	$imageName = $_FILES['image_2']['tmp_name'];
	$newImageName = $user_id.'-'.mktime().'-2';

	//large dimensions
	$maxWidth = '700';
	$maxHeight = '466';
	$imgScale2a = imageScale($rootPath.'large/', $imageName, $newImageName, $maxWidth, $maxHeight);

	//small dimensions
	$maxWidth = '108';
	$maxHeight = '300';
	$imgScale2b = imageScale($rootPath.'small/', $imageName, $newImageName, $maxWidth, $maxHeight);

	if(strlen($imgScale2a['error']) == 0){

	// add image 2 to db

	$sql = "INSERT INTO images (string) VALUES ('".$imgScale2a['image']."')";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$img2_id = mysql_insert_id();

	}

	}

	if(isset($_FILES['image_3']['tmp_name']) && strlen($_FILES['image_3']['tmp_name']) > 0){

	$imageName = $_FILES['image_3']['tmp_name'];
	$newImageName = $user_id.'-'.mktime().'-3';

	//large dimensions
	$maxWidth = '700';
	$maxHeight = '466';
	$imgScale3a = imageScale($rootPath.'large/', $imageName, $newImageName, $maxWidth, $maxHeight);

	//small dimensions
	$maxWidth = '108';
	$maxHeight = '300';
	$imgScale3b = imageScale($rootPath.'small/', $imageName, $newImageName, $maxWidth, $maxHeight);

	if(strlen($imgScale3a['error']) == 0){

	// add image 3 to db

	$sql = "INSERT INTO images (string) VALUES ('".$imgScale3a['image']."')";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$img3_id = mysql_insert_id();

	}

	}


// tradesmans trade?

	$sql = "SELECT tradesman_to_trade.id FROM tradesman 
	LEFT JOIN tradesman_to_trade ON tradesman.id = tradesman_to_trade.tradesman_id 
	WHERE tradesman.user_id = '".$user_id."' AND tradesman_to_trade.trade_id = '".$_POST['trades']."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$own_trades = mysql_num_rows($query);

// VALIDATE

$fail.= (strlen($imgScale1a['error']) > 0) ? '<li>Image 1: '.$imgScale1a['error'].'</li>' : '';
$fail.= (strlen($imgScale2a['error']) > 0) ? '<li>Image 2: '.$imgScale2a['error'].'</li>' : '';
$fail.= (strlen($imgScale3a['error']) > 0) ? '<li>Image 3: '.$imgScale3a['error'].'</li>' : '';
$fail.= (strlen($_POST['job_title']) == 0) ? '<li>Job title was not entered</li>' : '';
$fail.= (strlen($_POST['trades']) == 0) ? '<li>Trade was not selected</li>' : '';
$fail.= ($_POST['address_select'] == '0' && strlen($_POST['line_1']) == 0 && strlen($_POST['city']) == 0 && strlen($_POST['postcode']) == 0) ? '<li>Address was not entered</li>' : '';
$fail.= (strlen($_POST['job_description']) ==  0) ? '<li>Job description was not entered</li>' : '';
$fail.= ($own_trades > 0) ? '<li>You cannot post jobs for trades your company operates under</li>' : '';

if(strlen($fail) == 0){

require_once("classes/class.phpmailer.php");

if($_POST['address_select'] == '0'){

// INSERT NEW ADDRESS

	// google map

	$sql = "SELECT area FROM areas WHERE id = '".mysql_real_escape_string($_POST['city'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rs=mysql_fetch_assoc($query);

	$address = $_POST['line_1'].",".$_POST['line_2'].",".$_POST['line_3'].",".$rs['area'].",".$_POST['postcode'];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://maps.google.com/maps/geo?q=".urlencode($address)."&output=csv&oe=utf8&sensor=false&key=".$settings['google_api_key']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
	$outputArr = explode(",",$output);

	$sql="INSERT INTO addresses (user_id, area_id, line_1, line_2, line_3, postcode, longitude, latitude) VALUES ('".$user_id."', '".mysql_real_escape_string($_POST['city'])."', '".mysql_real_escape_string(stripslashes($_POST['line_1']))."', '".mysql_real_escape_string(stripslashes($_POST['line_2']))."', '".mysql_real_escape_string(stripslashes($_POST['line_3']))."', '".mysql_real_escape_string($_POST['postcode'])."', '".$outputArr[3]."', '".$outputArr[2]."')";
	$query=mysql_query( $sql ) or die ("Error in query: $sql. " . mysql_error());
	$_POST['address_select'] = mysql_insert_id();
}

else{

	$sql = "SELECT area_id FROM addresses WHERE id = '".mysql_real_escape_string($_POST['address_select'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rs=mysql_fetch_assoc($query);
	$_POST['city'] = $rs['area_id'];

}

$custom = (strlen($_POST['custom']) > 0) ? 1 : 0 ;

// INSERT DATA

	$sql = "INSERT INTO jobs (user_id, address_id, area_id, trade_id, date_added, title, description, custom, materials, status) VALUES ('".$user_id."','".mysql_real_escape_string($_POST['address_select'])."','".mysql_real_escape_string($_POST['city'])."','".mysql_real_escape_string($_POST['trades'])."', NOW(),'".mysql_real_escape_string(stripslashes($_POST['job_title']))."','".mysql_real_escape_string(stripslashes($_POST['job_description']))."','".$custom."', '".mysql_real_escape_string($_POST['materials'])."', 'Pending')";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$job_id = mysql_insert_id();

// HANDLE IMAGES

if(isset($img1_id)){
	$sql = "UPDATE images SET job_id = '".$job_id."' WHERE id = '".$img1_id."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
}

if(isset($img2_id)){
	$sql = "UPDATE images SET job_id = '".$job_id."' WHERE id = '".$img2_id."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
}

if(isset($img3_id)){
	$sql = "UPDATE images SET job_id = '".$job_id."' WHERE id = '".$img3_id."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
}

if(strlen($_POST['custom']) > 0){

// INSERT CUSTOM QUOTE

	$sql = "INSERT INTO job_to_tradesman (job_id, tradesman_id) VALUES ('".$job_id."','".mysql_real_escape_string($_POST['custom'])."')";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
}


// EMAIL FOR MODERATION

	$mail1 = new PHPMailer();
	$mail1->IsSMTP(); // telling the class to use SMTP
	$mail1->Host = "localhost"; // SMTP server
	$mail1->From = $settings['no_reply_email'];
	$mail1->FromName = "I Want A Tradesman";

	$mail1->AddAddress($settings['site_email']);

	$mail1->Subject = "New job awaiting moderation";
	$mail1->Body = "http://www.iwantatradesman.co.uk/admin/";

	$mail1->Send();

// EMAIL CONFIRMATION

	$mail2 = new PHPMailer();
	$mail2->IsSMTP(); // telling the class to use SMTP
	$mail2->Host = "localhost"; // SMTP server
	$mail2->From = $settings['no_reply_email'];
	$mail2->FromName = "I Want A Tradesman";

	$mail2->AddAddress($_POST['email1']);

	$mail2->Subject = "Job post confirmation";
	$mail2->Body = "Dear ".$rs['firstname']." ".$rs['surname']."\r\n\r\nThis email is to confirm that your job \"".$_POST['job_title']."\" has been successfully posted on I Want A Tradesman and is currently pending moderation.\r\n\r\nWe will email you again to confirm that your job has been accepted and published for quotation from local tradesman.\r\n\r\nKind regards\r\n\r\nThe I Want A Tradesman Team\r\n\r\n\r\nThis email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. This message contains confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately by e-mail if you have received this e-mail by mistake and delete this e-mail from your system. If you are not the intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance on the contents of this information is strictly prohibited.";

	$mail2->Send();


// REDIRECT TO ACCOUNT PAGE WITH RESULT

header("Location: /my-account?postjob=1".$imgResults);

}

else{

// FAILED VALIDATION

$results = '<p style="color: #cc0000; font-weight: bold;">Please correct the follwing errors:</p><ul style="color: #cc0000; font-weight: bold;">'.$fail.'</ul>';

}

}

// check for custom

if(isset($_GET['custom'])){

	$sql = "SELECT id, username, company_name FROM tradesman WHERE id = '".mysql_real_escape_string($_GET['custom'])."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rs=mysql_fetch_assoc($query);

	$custom_quote_content = '<p>You are requesting a quote from: <strong>'.ucfirst($rs['company_name']).'</strong></p>
				 <p>Note: This tradesman\'s trade must fall under the jobs trade.</p>
				 <input type="hidden" name="custom" id="custom" value="'.$rs['id'].'" style="display: none" />';

}

// load trades

	$sql = "SELECT id, trade FROM trades ORDER BY trade";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

	$trades_dropdown_content = '';

	while($rs=mysql_fetch_assoc($query)){
	$trades_dropdown_content.= '<option value="'.$rs['id'].'">'.htmlspecialchars($rs['trade']).'</option>'."\r\n";
	}

// load areas

	$sql = "SELECT id, area FROM areas ORDER BY area";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

	$areas_dropdown_content = '';

	while($rs=mysql_fetch_assoc($query)){
	$areas_dropdown_content.= '<option value="'.$rs['id'].'">'.htmlspecialchars($rs['area']).'</option>'."\r\n";
	}

	$area_dropdown = '<select name="city" id="city" onchange="return updateMainArea();" class="textbox" disabled="disabled"><option value="">Please select</option>'.$areas_dropdown_content.'</select>';

// load addresses

	$sql = "SELECT id, line_1, postcode FROM addresses WHERE user_id = '".$user_session[0]."' ORDER BY id";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());

	$i = 1;

	while($rs=mysql_fetch_assoc($query)){

	$checked = ($i == 1) ? ' checked="checked"' : '' ;

	$addresses_content.= '<input type="radio" id="address_select_'.$i.'" name="address_select" value="'.$rs['id'].'" onclick="return addressEnabler();"'.$checked.' /> <label for="address_select_'.$i.'">'.$rs['line_1'].' - '.$rs['postcode'].'</label><br />';

	$i++;

	}


include('includes/meta.php');
include('includes/header.php');
include('includes/navigation.php');

?>

<h1>Post a job</h1>

<?php echo $results; ?>

<div id="error_div" style="display: none;"></div>

<p>Please complete the form below to post a job on <strong>I Want A Tradesman</strong>. There are no charges for posting jobs and your details are 100% secure. Tradesmen will not see any of your contact information until you personally accept a quote from them. Please view our <a href="/privacy">privacy policy</a> for more information.</p>

<form method="post" action="/post-a-job.php" id="postjob" enctype="multipart/form-data">

<input type="hidden" id="form" name="form" value="postjob" style="display: none;" />

<?php echo $custom_quote_content; ?>

<div id="registration_form">

<div class="formAreaWrap">

<div class="rowWrapper" id="job_title_wrap">
<div class="rowLeft"><label for="job_title">Job title:</label></div>
<div class="rowRight"><input type="text" name="job_title" id="job_title" class="textbox" value="<?php echo $_POST['job_title']; ?>" /></div>
</div>

<div class="rowWrapper" id="trades_wrap">
<div class="rowLeft"><label for="trades">Trade required:</label></div>
<div class="rowRight"><select name="trades" id="trades" class="textbox">
<option value="">Please select</option>
<?php echo $trades_dropdown_content; ?>
</select></div>
</div>

</div>

<div id="address_wrap">

<div class="rowWrapper" id="address_select_wrap">
<div class="rowLeft"><label for="address_select_1">Address</label></div>
<div class="rowRight">
<?php echo $addresses_content; ?>
<input type="radio" id="address_select_0" name="address_select" value="0" onclick="return addressEnabler(1);" /> <label for="address_select_0">New address</label>
</div>
</div>

<div class="rowWrapper" id="line_1_wrap">
<div class="rowLeft"><label for="line_1">Address line 1:</label></div>
<div class="rowRight"><input type="text" name="line_1" id="line_1" class="textbox" value="<?php echo $_POST['line_1']; ?>" disabled="disabled" /></div>
</div>

<div class="rowWrapper" id="line_2_wrap">
<div class="rowLeft"><label for="line_2">Address line 2:</label></div>
<div class="rowRight"><input type="text" name="line_2" id="line_2" class="textbox" value="<?php echo $_POST['line_2']; ?>" disabled="disabled" /></div>
</div>

<div class="rowWrapper" id="line_3_wrap">
<div class="rowLeft"><label for="line_3">Address line 3:</label></div>
<div class="rowRight"><input type="text" name="line_3" id="line_3" class="textbox" value="<?php echo $_POST['line_3']; ?>" disabled="disabled" /></div>
</div>

<div class="rowWrapper" id="city_wrap">
<div class="rowLeft"><label for="city">Town/City:</label></div>
<div class="rowRight"><?php echo $area_dropdown; ?></div>
</div>

<div class="rowWrapper" id="postcode_wrap">
<div class="rowLeft"><label for="postcode">Postcode:</label></div>
<div class="rowRight"><input type="text" name="postcode" id="postcode" class="textbox" value="<?php echo $_POST['postcode']; ?>" style="width: 80px;" disabled="disabled" /></div>
</div>

</div>

<div class="formAreaWrap">

<div class="rowWrapper" id="job_description_wrap">
<div class="rowLeft"><label for="job_description">Job description:</label></div>
<div class="rowRight"><textarea name="job_description" id="job_description" class="textbox" rows="6" cols="30" placeholder="Explain your job in detail. eg; approx sizes etc. The more detail you give, the more accurate your quote will be."><?php echo $_POST['job_description']; ?></textarea></div>
</div>

<div class="rowWrapper" id="materials_wrap">
<div class="rowLeft"><label for="materials_1">Materials provided:</label></div>
<div class="rowRight"><input type="radio" name="materials" id="materials_1" value="1" checked="checked" /> <label for="materials_1">I will provide the materials</label><br />
<input type="radio" name="materials" id="materials_2" value="0" /> <label for="materials_2">Tradesman to provide materials</label></div>
</div>

</div>

<input type="hidden" name="total_images" id="total_images" value="1" style="display: none;" />
<p><strong>Note: You may have a maximum of 3 images for your job.</strong></p>

<div class="rowWrapper" id="image_wrap">
<div class="rowLeft"><label for="image_1">Images:</label><br /><span>(2mb Max)</span></div>
<div class="rowRight">
<div id="image_uploads">
<div class="image_upload_container"><input type="file" name="image_1" id="image_1" class="textbox" /></div>
</div>
<div id="addImageLink"><a onclick="return addImageInput(1);">Add another</a></div>

</div>
</div>

<div class="formRowWrapper">
<div class="formRowLeft">&nbsp;</div>
<div class="formRowMiddle"><input type="image" src="/images/postjob_button.gif" alt="Post job" /></div>
</div>

</div>

</form>

<div style="display: none;"><img src="images/tick.png" alt="" /><img src="images/cross.png" alt="" /></div>

<?php 

include('includes/rightColumn.php');
include('includes/footer.php');

?>                               